import java.util.concurrent.Callable;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class MySellTickets implements Runnable {
    private int num = 100;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();
    @Override
    public void run() {
        while (true) {
            lock.lock();
            try {
                if (num > 0) {
                    Thread.sleep(100);
                    String name = Thread.currentThread().getName();
                    System.out.println(name + "卖出了第" + num + "张票");
                    num--;
                    condition.await();
                    condition.signal();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }

    }


    public synchronized void sell() {
        if (num > 0) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(num);
            num--;
        }
    }
}
